package com.smart.translator;

import android.Manifest;
import android.content.ClipboardManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.smart.translator.R;
import com.smart.translator.service.FloatWindowService;
import com.smart.translator.service.PasteAccessibilityService;
import com.smart.translator.service.VoskSpeechService;
import com.smart.translator.util.WechatLogcatMonitor;
import com.smart.translator.util.BlePermissionHelper;
import com.smart.translator.util.PowerManagerHelper;
import com.smart.translator.data.ConfigApiService;
import com.smart.translator.data.OtaUpgradeService;
import com.smart.translator.ota.OtaManager;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import android.content.Context;
import android.content.IntentFilter;

public class MainActivity extends AppCompatActivity implements com.smart.translator.ota.OtaManager.OtaCallback {
    private static final int REQUEST_PERMISSIONS = 1;
    private NavController navController;
    private BottomNavigationView bottomNav;
    private ClipboardManager clipboardManager;
    private ClipboardManager.OnPrimaryClipChangedListener clipChangedListener;
    
    // Vosk服务监控
    private Handler serviceMonitorHandler;
    private Runnable serviceMonitorRunnable;
    private static final int SERVICE_MONITOR_INTERVAL = 30000; // 30秒检查一次

    // 新增：全局悬浮窗控制广播接收器
    private android.content.BroadcastReceiver floatWindowControlReceiver;
    
    // 新增：OTA升级服务
    private OtaUpgradeService otaUpgradeService;
    private Handler otaCheckHandler;
    private static final int OTA_CHECK_DELAY = 5000; // 5秒后检查OTA升级

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // 检查并请求权限（在启动服务之前）
        checkAndRequestPermissions();
        
        // 启动服务监控
        startServiceMonitoring();
        
        // 检查电源管理设置
        checkPowerManagement();
        
        // 设置导航
        NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager()
                .findFragmentById(R.id.nav_host_fragment);
        if (navHostFragment != null) {
            navController = navHostFragment.getNavController();
            bottomNav = findViewById(R.id.bottom_nav);
            NavigationUI.setupWithNavController(bottomNav, navController);
        }
        
        // 设置剪贴板监听
        setupClipboardListener();
        
        // 检查无障碍服务
        //checkAccessibilityService();

        registerFloatWindowControlReceiver(); // 新增
        
        // 新增：初始化OTA升级服务
        initOtaUpgradeService();
    }
    
    /**
     * 初始化OTA升级服务
     */
    private void initOtaUpgradeService() {
        otaUpgradeService = new OtaUpgradeService(this);
        otaCheckHandler = new Handler(Looper.getMainLooper());
        
        // 设置OtaManager回调
        OtaManager.getInstance().setCallback(this);
        
        // 获取服务器配置并设置基础URL
        ConfigApiService.getAppConfig().thenAccept(response -> {
            if (response.isSuccess()) {
                String serverUrl = response.getData().getServerUrl();
                if (serverUrl != null && !serverUrl.isEmpty()) {
                    // 确保URL以http://开头
                    if (!serverUrl.startsWith("http://") && !serverUrl.startsWith("https://")) {
                        serverUrl = "http://" + serverUrl;
                    }
                    otaUpgradeService.setBaseUrl(serverUrl);
                    android.util.Log.d("MainActivity", "OTA升级服务基础URL设置: " + serverUrl);
                    
                    // // 延迟检查OTA升级
                    // otaCheckHandler.postDelayed(() -> {
                    //     checkOtaUpgrade();
                    // }, OTA_CHECK_DELAY);
                } else {
                    android.util.Log.w("MainActivity", "服务器URL为空，跳过OTA升级检查");
                }
            } else {
                android.util.Log.e("MainActivity", "获取应用配置失败: " + response.getMessage());
            }
        });
    }
    
    /**
     * 检查OTA升级（由设备连接成功后调用）
     */
    public void checkOtaUpgrade() {
        android.util.Log.d("MainActivity", "开始检查OTA升级...");
        otaUpgradeService.checkAndPromptUpgrade();
    }
    
    /**
     * 启动BLE前台服务
     */
    private void startBleForegroundService() {
        try {
            android.util.Log.d("MainActivity", "开始启动BLE前台服务...");
            
            // 检查前台服务权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.FOREGROUND_SERVICE_MICROPHONE) != PackageManager.PERMISSION_GRANTED) {
                    android.util.Log.w("MainActivity", "前台服务权限未授予，跳过BLE前台服务启动");
                    return;
                }
            }
            
            // 启动BLE前台服务，确保长连接
            com.smart.translator.service.BleForegroundService.startService(this);
            android.util.Log.d("MainActivity", "BLE前台服务启动请求已发送");
        } catch (Exception e) {
            android.util.Log.e("MainActivity", "启动BLE前台服务失败", e);
        }
    }

    /**
     * 启动Vosk语音识别服务
     */
    private void startVoskSpeechService() {
        try {
            android.util.Log.d("MainActivity", "开始启动Vosk语音识别服务...");
            
            // 检查前台服务权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.FOREGROUND_SERVICE_MICROPHONE) != PackageManager.PERMISSION_GRANTED) {
                    android.util.Log.w("MainActivity", "前台服务权限未授予，跳过Vosk服务启动");
                    return;
                }
            }
            
            Intent intent = new Intent(this, VoskSpeechService.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(intent);
            } else {
                startService(intent);
            }
            android.util.Log.d("MainActivity", "Vosk语音识别服务启动请求已发送");
        } catch (Exception e) {
            android.util.Log.e("MainActivity", "启动Vosk服务失败", e);
        }
    }
    
    /**
     * 启动服务监控
     */
    private void startServiceMonitoring() {
        serviceMonitorHandler = new Handler(Looper.getMainLooper());
        serviceMonitorRunnable = new Runnable() {
            @Override
            public void run() {
                checkAndRestartVoskService();
                serviceMonitorHandler.postDelayed(this, SERVICE_MONITOR_INTERVAL);
            }
        };
        serviceMonitorHandler.post(serviceMonitorRunnable);
    }
    
    /**
     * 检查并重启Vosk服务
     */
    private void checkAndRestartVoskService() {
        if (!VoskSpeechService.isServiceRunning(this)) {
            android.util.Log.w("MainActivity", "检测到Vosk服务未运行，正在重启...");
            startVoskSpeechService();
        } else {
            android.util.Log.d("MainActivity", "Vosk服务运行正常");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (clipboardManager != null && clipChangedListener != null) {
            clipboardManager.removePrimaryClipChangedListener(clipChangedListener);
            android.util.Log.d("MainActivity", "已注销剪贴板监听");
        }
        
        // 停止服务监控
        if (serviceMonitorHandler != null && serviceMonitorRunnable != null) {
            serviceMonitorHandler.removeCallbacks(serviceMonitorRunnable);
        }

        if (floatWindowControlReceiver != null) {
            unregisterReceiver(floatWindowControlReceiver);
            floatWindowControlReceiver = null;
        }
        
        // 新增：清理OTA升级服务
        if (otaCheckHandler != null) {
            otaCheckHandler.removeCallbacksAndMessages(null);
            android.util.Log.d("MainActivity", "已清理OTA升级服务");
        }
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        // 应用回到前台时检查服务状态
        checkAndRestartVoskService();
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        // 应用进入后台时确保服务正在运行
        if (!VoskSpeechService.isServiceRunning(this)) {
            android.util.Log.w("MainActivity", "应用进入后台，Vosk服务未运行，正在启动...");
            startVoskSpeechService();
        }
    }

    private void checkAndRequestPermissions() {
        List<String> permissionsToRequest = new ArrayList<>();
        
        android.util.Log.d("Permissions", "=== 开始检查权限 ===");
        android.util.Log.d("Permissions", "Android版本: " + Build.VERSION.SDK_INT + " (API " + Build.VERSION.SDK_INT + ")");
        android.util.Log.d("Permissions", "Android版本名称: " + Build.VERSION.RELEASE);
        
        // 强制检查每个权限的状态
        android.util.Log.d("Permissions", "=== 检查各个权限状态 ===");
        
        // 检查录音权限
        boolean hasRecordAudio = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
        android.util.Log.d("Permissions", "RECORD_AUDIO 权限状态: " + (hasRecordAudio ? "已授予" : "未授予"));
        
        // 检查前台服务权限
        boolean hasForegroundServiceMicrophone = false;
        if (Build.VERSION.SDK_INT >= 34) {
            hasForegroundServiceMicrophone = ContextCompat.checkSelfPermission(this, Manifest.permission.FOREGROUND_SERVICE_MICROPHONE) == PackageManager.PERMISSION_GRANTED;
            android.util.Log.d("Permissions", "FOREGROUND_SERVICE_MICROPHONE 权限状态: " + (hasForegroundServiceMicrophone ? "已授予" : "未授予"));
        } else {
            android.util.Log.d("Permissions", "Android版本低于14，不需要前台服务权限");
        }
        
        // Android 12及以上版本需要的权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.BLUETOOTH_SCAN);
                android.util.Log.d("Permissions", "需要申请 BLUETOOTH_SCAN 权限");
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.BLUETOOTH_CONNECT);
                android.util.Log.d("Permissions", "需要申请 BLUETOOTH_CONNECT 权限");
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADVERTISE) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.BLUETOOTH_ADVERTISE);
                android.util.Log.d("Permissions", "需要申请 BLUETOOTH_ADVERTISE 权限");
            }
        } else {
            // Android 11及以下版本需要的权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.BLUETOOTH);
                android.util.Log.d("Permissions", "需要申请 BLUETOOTH 权限");
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.BLUETOOTH_ADMIN);
                android.util.Log.d("Permissions", "需要申请 BLUETOOTH_ADMIN 权限");
            }
        }

        // 位置权限（Android 12以下需要，但BLE前台服务也需要）
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.ACCESS_FINE_LOCATION);
                android.util.Log.d("Permissions", "需要申请 ACCESS_FINE_LOCATION 权限");
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.ACCESS_COARSE_LOCATION);
                android.util.Log.d("Permissions", "需要申请 ACCESS_COARSE_LOCATION 权限");
            }
        } else {
            // Android 12及以上版本，BLE前台服务仍然需要位置权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.ACCESS_FINE_LOCATION);
                android.util.Log.d("Permissions", "需要申请 ACCESS_FINE_LOCATION 权限 (BLE前台服务)");
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.ACCESS_COARSE_LOCATION);
                android.util.Log.d("Permissions", "需要申请 ACCESS_COARSE_LOCATION 权限 (BLE前台服务)");
            }
        }

        // 录音权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            permissionsToRequest.add(Manifest.permission.RECORD_AUDIO);
            android.util.Log.d("Permissions", "需要申请 RECORD_AUDIO 权限");
        }

        // Android 14及以上版本需要的前台服务权限
        if (Build.VERSION.SDK_INT >= 34) { // Android 14 (API 34)
            android.util.Log.d("Permissions", "检查前台服务权限 (Android 14+) - API " + Build.VERSION.SDK_INT);
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.FOREGROUND_SERVICE_MICROPHONE) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.FOREGROUND_SERVICE_MICROPHONE);
                android.util.Log.d("Permissions", "需要申请 FOREGROUND_SERVICE_MICROPHONE 权限");
            } else {
                android.util.Log.d("Permissions", "FOREGROUND_SERVICE_MICROPHONE 权限已授予");
            }
            
            // 检查前台服务位置权限（BLE前台服务需要）
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.FOREGROUND_SERVICE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(Manifest.permission.FOREGROUND_SERVICE_LOCATION);
                android.util.Log.d("Permissions", "需要申请 FOREGROUND_SERVICE_LOCATION 权限");
            } else {
                android.util.Log.d("Permissions", "FOREGROUND_SERVICE_LOCATION 权限已授予");
            }
        } else {
            android.util.Log.d("Permissions", "Android版本低于14，不需要前台服务权限 - API " + Build.VERSION.SDK_INT);
        }

        if (!permissionsToRequest.isEmpty()) {
            android.util.Log.d("Permissions", "请求权限: " + permissionsToRequest);
            ActivityCompat.requestPermissions(this, permissionsToRequest.toArray(new String[0]), REQUEST_PERMISSIONS);
        } else {
            android.util.Log.d("Permissions", "所有权限已授予");
            // 权限都已授予，启动服务
            startBleForegroundService();
            startVoskSpeechService();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        
        // 处理BLE权限结果
        if (requestCode == com.smart.translator.util.BlePermissionHelper.REQUEST_BLE_PERMISSIONS) {
            boolean allGranted = com.smart.translator.util.BlePermissionHelper.handlePermissionResult(requestCode, permissions, grantResults);
            if (!allGranted) {
                Toast.makeText(this, "需要BLE权限才能使用完整功能", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        
        if (requestCode == REQUEST_PERMISSIONS) {
            boolean allGranted = true;
            boolean microphonePermissionGranted = true;
            
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                    android.util.Log.e("Permissions", "权限被拒绝: " + permissions[i]);
                    
                    // 检查前台服务权限是否被拒绝
                    if (Manifest.permission.FOREGROUND_SERVICE_MICROPHONE.equals(permissions[i])) {
                        microphonePermissionGranted = false;
                    }
                }
            }
            
            if (!allGranted) {
                if (!microphonePermissionGranted) {
                    // 前台服务权限被拒绝，显示特殊提示
                    new AlertDialog.Builder(this)
                        .setTitle("权限提示")
                        .setMessage("前台服务权限被拒绝，应用可能无法正常工作。请在设置中手动授予前台服务权限。")
                        .setPositiveButton("去设置", (dialog, which) -> {
                            // 打开应用设置页面
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            intent.setData(android.net.Uri.fromParts("package", getPackageName(), null));
                            startActivity(intent);
                        })
                        .setNegativeButton("取消", null)
                        .show();
                } else {
                    Toast.makeText(this, "需要相关权限才能使用完整功能", Toast.LENGTH_SHORT).show();
                }
            } else {
                android.util.Log.d("Permissions", "所有权限已授予");
                // 权限都授予了，启动服务
                startBleForegroundService();
                startVoskSpeechService();
            }
        }
    }

    // 检查无障碍服务是否已开启
    public static boolean isAccessibilityServiceEnabled(Context context, Class<?> service) {
        String prefString = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
        if (prefString == null) return false;
        String serviceId = context.getPackageName() + "/" + service.getName();
        return prefString.contains(serviceId);
    }

    private void checkPowerManagement() {
        // 检查电源管理设置
        PowerManagerHelper.requestIgnoreBatteryOptimizations(this);
    }
    
    private void setupClipboardListener() {
        // 设置剪贴板监听
        clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        clipChangedListener = () -> {
            // 剪贴板内容变化时，发送广播通知PasteAccessibilityService
            Intent intent = new Intent("ACTION_TRIGGER_WECHAT_PASTE");
            sendBroadcast(intent);
            android.util.Log.d("MainActivity", "剪贴板内容变化，已发送ACTION_TRIGGER_WECHAT_PASTE广播");
        };
        if (clipboardManager != null) {
            clipboardManager.addPrimaryClipChangedListener(clipChangedListener);
            android.util.Log.d("MainActivity", "已注册剪贴板监听");
        }
    }
    
    private void checkAccessibilityService() {
        // 启动时检测无障碍服务是否已开启
        if (!isAccessibilityServiceEnabled(this, PasteAccessibilityService.class)) {
            new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("请开启无障碍服务以实现自动粘贴功能")
                .setPositiveButton("去开启", (dialog, which) -> {
                    Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                })
                .setNegativeButton("取消", null)
                .show();
        }
    }

    private void registerFloatWindowControlReceiver() {
        floatWindowControlReceiver = new android.content.BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                            android.util.Log.d("MainActivity", "收到悬浮窗广播");

                if ("com.smart.translator.ACTION_FLOAT_WINDOW_CONTROL".equals(intent.getAction())) {
                    boolean show = intent.getBooleanExtra("show", true);
                    if (show) {
                        FloatWindowService.requestAndShowFloatWindow(context);
                    } else {
                        context.stopService(new Intent(context, FloatWindowService.class));
                    }
                }
            }
        };
        IntentFilter filter = new IntentFilter("com.smart.translator.ACTION_FLOAT_WINDOW_CONTROL");
        registerReceiver(floatWindowControlReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
    }
    
    // OtaCallback 接口实现
    @Override
    public void onProgress(int progress, String message) {
        android.util.Log.d("MainActivity", "OTA进度: " + progress + "% - " + message);
    }
    
    @Override
    public void onSuccess(String message) {
        android.util.Log.d("MainActivity", "OTA成功: " + message);
        Toast.makeText(this, "OTA升级成功: " + message, Toast.LENGTH_SHORT).show();
    }
    
    @Override
    public void onError(String error) {
        android.util.Log.e("MainActivity", "OTA错误: " + error);
        Toast.makeText(this, "OTA升级失败: " + error, Toast.LENGTH_SHORT).show();
    }
    
    @Override
    public void onVersionReceived(String version) {
        android.util.Log.d("MainActivity", "收到版本信息: " + version);
    }
    
    @Override
    public void onVersionReceived(OtaManager.OtaType otaType, String version) {
        android.util.Log.d("MainActivity", "收到" + otaType.getDisplayName() + "版本信息: " + version);
    }
    
    @Override
    public void onVersionCheckComplete() {
        android.util.Log.d("MainActivity", "版本检查完成，开始检查OTA升级");
        // 在这里调用MainActivity的checkOtaUpgrade方法
        checkOtaUpgrade();
    }
} 